<template>
  <a-modal
    title="PDA菜单授权"
    width="600px"
    :visible="visible"
    dialogClass="zero-modal"
    @cancel="handleCancel"
  >
    <div class="system-role-pda-menu-modal">
       <a-collapse v-model="activeKey">
         <a-collapse-panel v-for="(itema,indexa) in menus" :key="String(indexa)" :header="itema.workShopName">
           <div class="menu-lists">
             <div class="menu-item" v-for="(itemb,indexb) in (itema.wmsPdaPowerOutput || [])" :key="`${indexa}-${indexb}`">
               <a-checkbox :checked="itemb.isCheck" @change="onChangeChecked(itemb)">{{itemb.name}}</a-checkbox>
             </div>
           </div>
         </a-collapse-panel>
       </a-collapse>
    </div>
    <template slot="footer">
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button type="primary" key="ok" @click="onConfirm">确认</a-button>
    </template>
  </a-modal> 
</template>

<script>
import { getPdaMenuList } from '@/api/modular/system/menuManage'
import { sysRoleGrantPdaMenu } from '@/api/modular/system/roleManage'

export default {
  name:'systemRolePdaMenuModal',
  emits:['update:visible'],
  props:{
    visible:{
      type:Boolean,
      default:false
    },
    roleid:{
      type:[Number,String,null],
      default:null
    }
  },
  data(){
    return {
      menus:[],
      activeKey:[]
    }
  },
  watch:{
    visible(newV,oldV){
      if (newV!==oldV){
        this.initShow()
      }
    }
  },
  methods:{
    handleCancel(){
      this.$emit('update:visible',false)
    },
    initShow(){
      if (this.visible) {
        this.getMenus()
      }
    },
    getMenus(){
      this.$loading.show()
      getPdaMenuList(this.roleid).then((d)=>{
        this.menus = d.data || []
        if (this.menus.length>0) {
          this.activeKey = ['0']
        }
        this.$loading.hide()
      }).catch(()=>{
        this.$loading.hide()
      })
    },
    onChangeChecked(row){
      row.isCheck = !row.isCheck
    },
    onConfirm(){
      this.$loading.show()
      this.handleUpdateAjax((f)=>{
        this.$loading.hide()
        if (f) {
          this.$message.success('操作成功！');
          this.handleCancel()
        }
      })
    },
    handleUpdateAjax(callback){
      let _params = {
        id:this.roleid,
        grantMenuIdList:[]
      }
      this.menus.forEach((itema)=>{
        if (itema.wmsPdaPowerOutput instanceof Array) {
          itema.wmsPdaPowerOutput .forEach((itemb)=>{
            if (itemb.isCheck){
              _params.grantMenuIdList.push(itemb.id)
            }
          })
        }
      })
      if (_params.grantMenuIdList.length<=0) {
        callback(false)
      } else {
        sysRoleGrantPdaMenu(_params).then(()=>{
          callback(true)
        }).catch(()=>{
          callback(false)
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.system-role-pda-menu-modal{
  padding: 16px;
}
</style>